package com.ukefu.webim.web.handler.api.rest;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.ukefu.util.Menu;
import com.ukefu.webim.service.cache.CacheHelper;
import com.ukefu.webim.service.repository.ExtentionRepository;
import com.ukefu.webim.service.repository.PbxHostRepository;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.Extention;
import com.ukefu.webim.web.model.PbxHost;
import com.ukefu.webim.web.model.User;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/api/extention")
@Api(value = "分机信息" , description = "获取当前登录用户的绑定分机信息")
public class ApiExtentionController extends Handler{
	

	@Autowired
	private ExtentionRepository extentionRes;
	
	@Autowired
	private PbxHostRepository pbxHostRes ;
	/**
	 * 返回当前登录用户绑定的分机信息
	 * @param request
	 * @param map
	 * @param namesid
	 * @param meta
	 * @return
	 */
	@RequestMapping( method = RequestMethod.GET)
	@Menu(type = "apps" , subtype = "extention" , access = true)
	@ApiOperation("返回当前坐席绑定的分机信息")
    public ModelAndView detail(HttpServletRequest request , ModelMap map ,@Valid String extno) {
		User user = super.getUser(request) ;
		Extention extention = null ;
		if(user!=null && !StringUtils.isBlank(user.getExtid())) {
			extention = extentionRes.findById(user.getExtid()) ;
		}else if(!StringUtils.isBlank(extno)) {
			List<Extention> extentionList = extentionRes.findByExtentionAndOrgi(extno, super.getOrgi(request)) ;
			if(extentionList!=null && extentionList.size() == 1){
				extention = extentionList.get(0) ;
			}
		}
		if(extention!=null) {
			PbxHost pbxHost = pbxHostRes.findById(extention.getHostid()) ;
			if(pbxHost!=null) {
				map.addAttribute("pbxhost" , pbxHost);
			}
			map.addAttribute("extention" , extention);
			map.addAttribute("agent" , CacheHelper.getCallCenterAgentCacheBean().getCacheObject(super.getUser(request).getId(), super.getOrgi(request)));

		}
		
    	return request(super.createRequestPageTempletResponse("/apps/business/callcenter/extention/detail"));
    }
}